<template>
  <div class="connnn">
    <div class="im-con-box">
      <im-head @updateUserType='getUserType' :user_type='user_type' />

      <div class="im_con">
        <div class="im_list">

          <!-- 搜索 -->
          <div class="im_list_head">
            <div>
              <el-input placeholder="请输入内容" v-model="search_2">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <div style="width: 30%;display: flex;justify-content: flex-end;align-items: center;cursor:pointer;" @click="search_attention()">
              搜索
            </div>
          </div>

          <!-- 关注的 -->
          <follow-lists v-if="user_type==0" :search='search_2' />

          <!-- 沟通的-->
          <conversation-list v-else />

        </div>

        <current-conversation :text='text' />

        <div class="im_material">
          <div class="material_tabs">
            <div :class="{im_active:sucai==1}" @click="sel_material(1)">常用语</div>
            <div :class="{im_active:sucai==2}" @click="sel_material(2)">常用链接</div>
            <div :class="{im_active:sucai==3}" @click="sel_material(3)">常用图片</div>
          </div>
          <mescroll-vue ref="mescroll" :down="mescrollDown" :up="mescrollUp" @init="mescrollInit">
            <div class="material_body" v-if="sucai == 1 ">
              <!--内容...-->
              <div class="material_item1" v-for="(item,i) in content" :key="i">
                <p @click="send_text($event,item)">
                  {{item.content}}</p>
              </div>
            </div>
            <div class="material_body" v-if="sucai == 2 ">
              <div class="material_item1" v-for="(item,i) in content" :key="i">
                <p @click="send_text($event,item)">
                  {{item.content}}</p>
              </div>
            </div>
            <div class="material_body2" v-if="sucai == 3">
              <div class="material_item3" v-for="(item,i) in content" :key="i">
                <img @click="cpimgOk(item.content)" :src="$fnc.getImgUrl(item.content)" alt="">
              </div>
            </div>
          </mescroll-vue>
        </div>

      </div>
    </div>

  </div>
</template>

<script>
import Vue from "vue";
import store from "../../assets/js/im.js";
import im from "../../assets/js/im/send_common_msg.js";
import compressimgUpload from "@/components/currency/compressimgUpload.vue";
import userinfo from "@/components/user/user_info.vue";
import img_view from "@/components/currency/big_img";
import MescrollVue from "mescroll.js/mescroll.vue"; //下拉组件

import conversationList from "./conversation/conversation-list";
import imHead from "./head/im-head";
import followLists from "./conversation/follow-lists";

import currentConversation from "./conversation/current-conversation";

import { mapGetters, mapState } from "vuex";
export default {
  components: {
    compressimgUpload,
    userinfo,
    MescrollVue,
    img_view,
    conversationList,
    imHead,
    followLists,
    currentConversation
  },
  destroyed: function () { },
  data () {
    let serverData = store.fetch();

    return {
      search_2: "",

      user_type: 1,
      content: [],
      sucai: 1,
      adminlist: this.$store.state.adminList,
      text: "",

      emoji: [],
      msgedit: "",
      scrollTop: 0,

      num: 1,
      index: 0,
      user: serverData.user,
      // 用户列表
      userList: [],
      // 会话列表
      textvalue: [],
      // 搜索key
      search: "",
      // 选中的会话Index

      remark: "未备注",

      mescroll: null, // mescroll实例对象
      mescrollDown: {
        mustToTop: true
      }, //下拉刷新的配置. (如果下拉刷新和上拉加载处理的逻辑是一样的,则mescrollDown可不用写了)
      mescrollUp: {
        // 上拉加载的配置.
        callback: this.upCallback, // 上拉回调,此处简写; 相当于 callback: function(page, mescroll) { }
        //以下是一些常用的配置,当然不写也可以的.
        page: {
          num: 0, //当前页 默认0,回调之前会加1; 即callback(page)会从1开始
          size: 10 //每页数据条数,默认10
        },
        htmlNodata: '<p class="upwarp-nodata">-- END --</p>',
        noMoreSize: 1, //如果列表已无数据,可设置列表的总数量要大于5才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看这就是为什么无更多数据有时候不显示的原因
        toTop: {
          //回到顶部按钮
          src: "./static/mescroll/mescroll-totop.png", //图片路径,默认null,支持网络图
          offset: 1000 //列表滚动1000px才显示回到顶部按钮
        },
        empty: {
          //列表第一页无任何数据时,显示的空提示布局; 需配置warpId才显示
          warpId: "", //父布局的id (1.3.5版本支持传入dom元素)
          icon: "./static/mescroll/mescroll-empty.png", //图标,默认null,支持网络图
          tip: "暂无相关数据~" //提示
        }
      }
    };
  },
  computed: {
    ...mapGetters(["toAccount", "currentConversationType"])
  },
  beforeRouteEnter (to, from, next) {
    // 如果没有配置回到顶部按钮或isBounce,则beforeRouteEnter不用写
    next(vm => {
      // 找到当前mescroll的ref,调用子组件mescroll-vue的beforeRouteEnter方法
      vm.$refs.mescroll && vm.$refs.mescroll.beforeRouteEnter(); // 进入路由时,滚动到原来的列表位置,恢复回到顶部按钮和isBounce的配置
      // 进入路由时,滚动到原来的列表位置,恢复回到顶部按钮和isBounce的配置
    });
  },
  beforeRouteLeave (to, from, next) {
    // 如果没有配置回到顶部按钮或isBounce,则beforeRouteLeave不用写
    // 找到当前mescroll的ref,调用子组件mescroll-vue的beforeRouteLeave方法
    this.$refs.mescroll && this.$refs.mescroll.beforeRouteLeave(); // 退出路由时,记录列表滚动的位置,隐藏回到顶部按钮和isBounce的配置
    // 退出路由时,记录列表滚动的位置,隐藏回到顶部按钮和isBounce的配置
    next();
  },
  methods: {
    getUserType (type) {
      this.user_type = type; //关注的 沟通中的切换
    },

    mescrollInit (mescroll) {
      this.mescroll = mescroll; // 如果this.mescroll对象没有使用到,则mescrollInit可以不用配置
    },
    upCallback (page, mescroll) {
      this.$api.getim
        .material_find({ page: page.num, types: this.sucai })
        .then(res => {
          if (res.data.code == 200) {
            let arr = res.data.result.data;
            // 如果是第一页需手动置空列表
            if (page.num === 1) this.content = [];
            // 下拉刷新
            // 把请求到的数据添加到列表
            this.content = this.content.concat(arr);
            // 数据渲染成功后,隐藏下拉刷新的状态
            this.$nextTick(() => {
              mescroll.endSuccess(arr.length);
            });
          } else {
            mescroll.endErr();
          }
        });
    },
    search_attention () {
      this.user_type = 0;
      this.$bus.$emit("getFollow");
    },

    send_text (e, item) {
      this.text = item.content;
    },
    sel_material (sucai) {
      //选择素材
      this.sucai = sucai;
      this.content = []; // 在这里手动置空列表,可显示加载中的请求进度
      this.mescroll.resetUpScroll(); // 刷新列表数据
    },

    sendImage (pic) {
      const message = this.tim.createImageMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: pic // 或者用event.target
        },
        onProgress: percent => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        }
      });

      this.$store.commit("pushCurrentMessageList", message);
      this.$bus.$emit("scroll-bottom");
      this.tim
        .sendMessage(message)
        .catch(imError => this.$message.error(imError.message));
    },
    cpimgOk (piclink) {
      const message = this.tim.createCustomMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          data: "piclinkmes",
          description: piclink,
          extension: ""
        }
      });
      this.tim.sendMessage(message).then((success) => {
        this.$store.commit("pushCurrentMessageList", message);
      }).catch((imError) => this.$message.error(imError.message));
    },
    convertBase64UrlToBlob (urlData) {
      let bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
      //处理异常,将ascii码小于0的转换为大于0
      let ab = new ArrayBuffer(bytes.length);
      let ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      return new Blob([ab], { type: "image/png" });
    },
    dataURLtoFile (dataurl, filename = "file") {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, { type: mime });
    }
  },
  created () { },
  watch: {},
  mounted () {
    // this.$bus.$on("selectUser", this.conversationItem);
  }
};
</script>


<style lang="less" scoped>
.im_list_head {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-items: center;
  color: #c5c8d0;
  padding: 10px 20px;
  height: 50px;
  background: #fff;
  border-bottom: 1px solid #efe6e6;
}
.im-con-box {
  display: flex;
  flex-direction: column;
  overflow: auto;
  height: 100%;
}
.mescroll {
  /*通过fixed固定mescroll的高度*/
  // position: fixed;
  // width: 400px;
  background: #ffffff;
  /*top: 44px;*/
  /*bottom: 0;*/
  height: 730px;
}

.text_img {
  width: 220px;
  // height: 180px;
}
.emojie_con {
  padding: 7px;
}
.connnn {
  background: #eef0f5;
  height: 100%;
}

.im_con {
  display: flex;
  justify-content: flex-start;
  overflow: auto;

  > .im_material {
    width: 15%;
    height: 100%;
    background: #ffffff;
    margin: 0 4px;
    word-break: break-all;
    overflow: hidden;
    > .material_tabs {
      height: 60px;
      background: #f9fafb;
      display: flex;
      flex-wrap: nowrap;
      justify-content: flex-start;
      align-items: flex-end;
      padding-left: 15px;
      > div {
        height: 50px;
        width: 120px;
        z-index: 14;
        position: relative;
        display: inline-block;
        padding-top: 20px;
        cursor: pointer;
        margin: 0 -4px;
      }
      > div::before {
        content: "";
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: -1;
        background: #f9fafb;
        border: 1px solid #eef0f5;
        border-bottom: none;
        border-radius: 0.5em 0.5em 0 0;
        transform: perspective(1.5em) rotateX(5deg);
        transform-origin: bottom;
      }
      .im_active::before {
        background: #fff;
      }
    }
    .material_body {
      width: 100%;
      /*height: calc(100vh - 230px);*/
      overflow-y: auto;
      display: flex;
      flex-flow: column;
      justify-content: flex-start;
      align-items: flex-start;
      margin-top: 20px;
      cursor: pointer;
      > .material_item1 {
        border-radius: 10px;
        border: 1px solid #cccccc;
        width: 90%;
        margin: 5px auto;
        p {
          padding: 0 10px;
          text-align: left;
          color: #000;
          line-height: 25px;
        }
      }
    }
    .material_body2 {
      width: 95%;
      overflow-y: auto;
      margin: 0 auto;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-evenly;
      align-items: center;
      margin-top: 20px;
      cursor: pointer;
      > .material_item3 {
        width: 40%;
        margin: 5px 0;
        img {
          width: 100%;
        }
      }
    }
  }
}
div.user_time {
  font-size: 13px;
  color: #9fa3bc;
  text-align: left;
}

.list:hover {
  background: #f2f5fa !important;
}

.msg_clos {
  display: flex;
  justify-content: flex-start;
  > div {
    padding: 10px;
  }
}

.bot_btn {
  color: #d1d4db !important;
  border: 1px solid #d1d4db !important;
  margin-left: 20px;
}
.list_actives {
  background: #f2f5fa !important;
}

.info {
  margin-left: 20px;
}

.info li {
  // display: inline-block;
  float: left;
  width: 33%;
  margin: 10px 0px 5px 0;
  text-align: left;
  padding-left: 10px;
}
.box {
  margin-left: 20px;
  margin-right: 20px;
  margin-top: 50px;
  border-bottom: 0 !important;
}

#attention_box {
  position: relative;
}
#user_list {
  overflow: auto;
}
.im_list {
  width: 350px;
  height: 760px;
  margin-right: 4px;
  background: #f9fafb;
  overflow: hidden;
}
</style>
